package com.example.productdataserviceprovider.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
public class RedisLockController extends BaseController {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    private int count=1000;
    private boolean flag=false;
    @RequestMapping("/buy")
    public String buy(Model model){
        String key="goods:id";
        String value=redisTemplate.opsForValue().get(key);


        if(StringUtils.hasText(value)){
            String result="不好意思，已经有人在用了";
            logger.info(result);
            return result;
        }
        if(redisTemplate.opsForValue().setIfAbsent(key,key, 10,TimeUnit.SECONDS)==true){
            count--;
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            logger.info(Thread.currentThread().getName()+"获取到:"+count);
            redisTemplate.delete(key);
        }else{
            logger.info(Thread.currentThread().getName()+"没有获取到");
        }
        return "剩余的产品数量:"+count;
    }
    @RequestMapping("/buy2")
    public String buy2(Model model){
        logger.info("Thread="+Thread.currentThread().getName()+" entered");
        if(flag){
            String result="不好意思，已经有人在用了";
            logger.info(result);
            return result;
        }
        if(!flag){
            flag=true;
            count--;
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            logger.info(Thread.currentThread().getName()+"获取到:"+count);
            flag=false;
        }else{
            logger.info(Thread.currentThread().getName()+"没有获取到");
        }

        return "剩余的产品数量:"+count;
    }
}
